package com.rock.sys.hotdev;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.util.StrUtil;
import org.apache.commons.io.FileUtils;

/**
 * 用于Maven多模块架构下实时扫描静态资源
 * @author jadison
 *
 */
public class RockResourceLoader {


    private String resourcePathName;
    private List<FileScanner> scanners = new ArrayList<>();

    public RockResourceLoader() {
        String configResourcePathName = "";
        this.resourcePathName = StrUtil.blankToDefault(configResourcePathName, "webapp");
    }

    public RockResourceLoader(String resourcePathName) {
    	if (StrUtil.isBlank(resourcePathName)) {
            throw new NullPointerException("Resource path name must not be blank.");
        }
    	this.resourcePathName = resourcePathName;
        
    }


    public void start() {
        try {

            URL url = RockResourceLoader.class.getClassLoader().getResource("");
            if (url == null) {
                return;
            }

            String classPath = url.toURI().getPath();
            File srcRootPath = new File(classPath, "../..").getCanonicalFile();

            if (new File(srcRootPath.getParent(), "pom.xml").exists()) {
                srcRootPath = srcRootPath.getParentFile();
            }

            List<File> resourcesDirs = new ArrayList<>();
            findResourcesPath(srcRootPath, resourcesDirs);

            for (File resourcesDir : resourcesDirs) {
                startNewScanner(resourcesDir.getCanonicalFile(), classPath);
            }

            Runtime.getRuntime().addShutdownHook(new Thread(() -> RockResourceLoader.this.stop()));
            System.err.println("RockResourceLoader started, Watched resource path name : " + resourcePathName);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void stop() {
        scanners.forEach(fileScanner -> fileScanner.stop());
        System.out.println("RockResourceLoader stoped ......");
    }

    private void findResourcesPath(File root, List<File> resourcesDirs) {
        File[] dirs = root.listFiles(pathname -> pathname.isDirectory());
        if (dirs == null || dirs.length == 0) {
            return;
        }
        for (File dir : dirs) {

            File parentFile = dir.getParentFile();
            if (parentFile == null) {
                return;
            }

            if (dir.getName().equals(resourcePathName)
                    && parentFile.getName().equals("main")) {
                resourcesDirs.add(dir);
            } else {
                findResourcesPath(dir, resourcesDirs);
            }
        }
    }


    private void startNewScanner(File resourcesDir, String classPath) throws IOException {
        // main/webapp/
        String path = "main" + File.separator + resourcePathName + File.separator;
        FileScanner scanner = new FileScanner(resourcesDir.getCanonicalPath(), 5) {
            @Override
            public void onChange(String action, String file) {
                if (FileScanner.ACTION_INIT.equals(action)) {
                    return;
                }

                int indexOf = file.indexOf(path);

                File target = new File(classPath, resourcePathName + File.separator + file.substring(indexOf + path.length()));
                System.err.println("RockResourceLoader " + action + " : " + target);

                //文件删除
                if (FileScanner.ACTION_DELETE.equals(action)) {
                    target.delete();
                }
                //新增文件 或 修改文件
                else {
                    try {
                        FileUtils.copyFile(new File(file), target);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        scanner.start();
        scanners.add(scanner);
    }

}
